import React from 'react';
import { inject, observer } from 'mobx-react';
import * as mobx from 'mobx';
import isEmpty from 'lodash/isEmpty';
import { Button, Popover, Carousel } from 'antd';
import { WeaLocaleProvider, WeaBrowser } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

import AddMenu from './AddMenu';
import DragSort from './DragSort';
import MoreMenus from './MoreMenus';
import BgImages from './BgImages';

@inject('portalDeskTopStore')
@observer
class E9DeskTop extends React.Component {
    constructor(props) {
        super(props);
        this.onPrev = this.onPrev.bind(this);
        this.onNext = this.onNext.bind(this);
        this.afterChange = this.afterChange.bind(this);
        this.shouldCancelStart = this.shouldCancelStart.bind(this);
    }

    componentWillMount() {
        const { portalDeskTopStore } = this.props;
        portalDeskTopStore.getDatas();
    }

    componentDidMount() {
        const { portalDeskTopStore } = this.props;
        const onWindowResize = () => {
            const width = jQuery('#e9desktopContentMiddle').width();
            const height = jQuery('#e9desktopContentMiddle').height();
            const menu_w_h = width * 0.1428;
            portalDeskTopStore.setState({ menu_w_h, rowNum: parseInt(height / menu_w_h) });
        };
        onWindowResize();
        jQuery(window).resize(() => onWindowResize());
    }

    render() {
        const { portalDeskTopStore } = this.props;
        const { bgImageObj, colNum, state, setState, setAddState, onSave, onSynchronize } = portalDeskTopStore;
        const { isSetting, isSystemer, datas, moreDatas, moreDatasVisible, rowNum, current, bgImagesVisible, imgid } = state;
        const { color } = bgImageObj;
        const _datas = mobx.toJS(datas);
        const _moreDatas = mobx.toJS(moreDatas);
        const menuNum = rowNum * colNum;
        const page = Math.ceil(_datas.length / menuNum);
        const last = page - 1;

        let displayComp = <div />;
        if (!isEmpty(_datas)) {
            if (_datas.length > menuNum) {
                let carouselItems = [];
                for (let i = 0; i < page; i++) {
                    let items = _datas.slice(i * menuNum, (i + 1) * menuNum);
                    carouselItems.push(
                        <div className="e9desktop-carousel-item">
                            <DragSort ecId={`${this && this.props && this.props.ecId || ''}_DragSort@kf0lgd@${i}`} isSetting={isSetting} datas={_datas} items={items} start={i * menuNum} num={menuNum} shouldCancelStart={this.shouldCancelStart} onSort={setState} />
                        </div>,
                    );
                }
                displayComp = (
                    <Carousel ecId={`${this && this.props && this.props.ecId || ''}_Carousel@honadl`} key={current} initialSlide={current} dots={true} afterChange={this.afterChange}>
                        {carouselItems}
                    </Carousel>
                );
            } else {
                displayComp = <DragSort ecId={`${this && this.props && this.props.ecId || ''}_DragSort@r39ymg`} isSetting={isSetting} items={_datas} shouldCancelStart={this.shouldCancelStart} onSort={setState} />;
            }
        }

        return (
            <div className="e9desktop-container"
              onClick={
                     (e) => {
                         let _moreDatasVisible = false;
                         let _bgImagesVisible = false;
                         const className = e.target.className;
                         if (className && className.indexOf('e9desktop-footer-icon') != -1) {
                             if (className.indexOf('wevicon-toolbar-more') != -1) {
                                 _moreDatasVisible = !moreDatasVisible;
                             } else if (className.indexOf('wevicon-e9login-palette') != -1) {
                                 _bgImagesVisible = !bgImagesVisible;
                             }
                         }
                         setState({ moreDatasVisible: _moreDatasVisible, bgImagesVisible: _bgImagesVisible });
                     }
                 }
            >
                <div className="e9desktop-content" style={{ color: color || '#fff' }}>
                    <div className="e9desktop-content-left">
                        <i
                          title={current > 0 ? getLabel(26029, '上一页') : ''}
                          className={`icon-coms-Left ${_datas.length > menuNum ? (current > 0 ? '' : 'e9desktop-display-none') : 'e9desktop-display-none'}`}
                          onClick={this.onPrev}
                        />
                    </div>
                    <div id="e9desktopContentMiddle" className={`e9desktop-content-middle ${isSetting ? 'e9desktop-content-setting' : 'e9desktop-content-view'}`}>
                        {displayComp}
                    </div>
                    <div className="e9desktop-content-right">
                        <i
                          title={current < last ? getLabel(26028, '下一页') : ''}
                          className={`icon-coms-Right ${_datas.length > menuNum ? (current < last ? '' : 'e9desktop-display-none') : 'e9desktop-display-none'}`}
                          onClick={this.onNext}
                        />
                    </div>
                </div>
                <div className="e9desktop-footer">
                    <AddMenu ecId={`${this && this.props && this.props.ecId || ''}_AddMenu@j24mse`} />
                    <div className={`e9desktop-footer-btns ${isSetting ? '' : 'e9desktop-display-none'}`}>
                        <div className="e9desktop-footer-btns-background" />
                        <div className="e9desktop-footer-btns-content" style={isSystemer ? { marginLeft: '-198px' } : {}}>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4p1202`} type="primary" onClick={() => setAddState({ visible: true, id: '', menuid: '', menutype: '1', menuname: '', menuicon: '', url: '', unreadapiaddr: '', replaceData: [] })}>{getLabel(387142, '添加应用')}</Button>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rwjdbn`} type="primary" onClick={() => onSave('')}>{getLabel(30986, '保存')}</Button>
                            {
                                isSystemer ?
                                    <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@j7qkia`}
                                      title={getLabel(33553, '分部')}
                                      type={194}
                                      customized
                                      isSingle={false}
                                      onChange={ids => onSynchronize(ids)}
                                    >
                                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@of80dg`} type="primary">{getLabel(387143, '同步到...')}</Button>
                                    </WeaBrowser> : ''
                            }
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vw6rah`} onClick={() => setState({ isSetting: false })}>{getLabel(31129, '取消')}</Button>
                        </div>
                    </div>
                    <div className={`e9desktop-footer-icons ${isSetting ? 'e9desktop-display-none' : ''}`}>
                        {
                            _moreDatas.length ? (
                                    <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@9wht4x`}
                                      trigger="click"
                                      placement="topLeft"
                                      content={<MoreMenus ecId={`${this && this.props && this.props.ecId || ''}_MoreMenus@dykimf`} />}
                                      overlayClassName="e9desktop-footer-icons-overlay"
                                      visible={moreDatasVisible}
                                      onVisibleChange={() => setState({ moreDatasVisible: true })}
                                    >
                                        <i style={{ left: 0 }} className={`wevicon-toolbar-more e9desktop-footer-icon ${imgid ? 'e9desktop-footer-icon-white' : 'e9desktop-footer-icon-dark'}`} title={getLabel(17499, '更多')} />
                                    </Popover>
                                ) : ''
                        }
                        <i style={{ left: 48 }} className={`icon-coms-Flow-setting e9desktop-footer-icon ${imgid ? 'e9desktop-footer-icon-white' : 'e9desktop-footer-icon-dark'}`} onClick={() => setState({ isSetting: true })} title={getLabel(131607, '应用管理')} />
                        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@smur54`}
                          trigger="click"
                          placement="topLeft"
                          content={<BgImages ecId={`${this && this.props && this.props.ecId || ''}_BgImages@ki034x`} />}
                          visible={bgImagesVisible}
                          onVisibleChange={() => setState({ bgImagesVisible: true })}
                        >
                            <i style={{ left: 96 }} className={`wevicon-e9login-palette e9desktop-footer-icon ${imgid ? 'e9desktop-footer-icon-white' : 'e9desktop-footer-icon-dark'}`} title={getLabel(387144, '背景自定义')} />
                        </Popover>
                    </div>
                </div>
            </div>
        );
    }

    onPrev() {
        const { portalDeskTopStore } = this.props;
        const { state } = portalDeskTopStore;
        let { current } = state;
        current -= 1;
        portalDeskTopStore.setState({ current: current < 0 ? 0 : current });
    }

    onNext() {
        const { portalDeskTopStore } = this.props;
        const { colNum, state } = portalDeskTopStore;
        let { current, rowNum } = state;
        let datas = mobx.toJS(state.datas);
        let last = Math.ceil(datas.length / (rowNum * colNum)) - 1;
        current += 1;
        portalDeskTopStore.setState({ current: current > last ? last : current });
    }

    afterChange(current) {
        const { portalDeskTopStore } = this.props;
        portalDeskTopStore.setState({ current });
    }

    shouldCancelStart(e) {
        const { portalDeskTopStore } = this.props;
        const { state } = portalDeskTopStore;

        const className = e.target.className;
        const index = parseInt(jQuery(e.target).parents('.e9desktop-item').attr('data-index'));
        const item = state.datas[index];

        if (className == 'e9desktop-item-icon' || className == 'e9desktop-item-icon-move' || className == 'e9desktop-item-icon-shadow' || className == 'e9desktop-item-icon-setting') {
            return false;
        }
        if (className == 'icon-coms-Need-feedback') {
            portalDeskTopStore.setAddState({ ...item, visible: true });
        }
        if (className == 'e9desktop-item-icon-delete' || className == 'anticon anticon-cross') {
            portalDeskTopStore.onDelete(index, item);
        }
        return true;
    }
}

export default E9DeskTop;
